package com.shambles.weixin.insweptcontroller;

import com.shambles.manage.model.Users;
import com.shambles.manage.service.UserService;
import com.shambles.manage.singleton.Singleton;
import com.shambles.manage.tools.verifycode.Captcha;
import com.shambles.manage.tools.verifycode.SpecCaptcha;
import com.shambles.weixin.controller.WechatSendMessageController;
import common.HttpClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Controller
@RequestMapping("/mobile/register1")
public class UserRegisterController {

	private UserService userService;

	@Autowired
	public void setUserService(UserService userService) {
		this.userService = userService;
	}

	/*
	 * 生成验证码类
	 */
	@RequestMapping(value="getYzm",method=RequestMethod.GET)
	public void getYzm(HttpServletResponse response,HttpServletRequest request){
		HttpSession session = request.getSession();
		try {
			response.setHeader("Pragma", "No-cache");
	        response.setHeader("Cache-Control", "no-cache");
	        response.setDateHeader("Expires", 0);
	        response.setContentType("image/jpeg");

	        //生成随机字串
	        Captcha captcha = new SpecCaptcha(120,25,4);

	        //生成图片
	        captcha.out(response.getOutputStream());
            String verifyCode=captcha.text().toLowerCase();
            session.setAttribute("verifyCode", verifyCode);
		} catch (Exception ex) {
			ex.printStackTrace();
		}
	}

	@RequestMapping("testName")
	public @ResponseBody Map<String, Object>
	testName(@RequestParam String name){
		Map<String, Object> map=new HashMap<>();

		int repeat=userService.selectRepeatUser(name);

		if(name.equals("")){
			map.put("data", "用户名不能空");
			return map;
		}


		String regEx="[`~!@#$%^&*()+=|{}':;',\\[\\].<>/?~！@#￥%……&*（）——+|{}【】‘；：”“’。，、？]";
		Pattern   p   =   Pattern.compile(regEx);
	    Matcher   m   =   p.matcher(name);

	    if(m.find()){
	    	map.put("data", "用户名含有非法字符");
			return map;
	    }

		if(repeat>=1){
			map.put("data", "该用户名已被注册，请使用其他用户名注册");
			return map;
		}else{
			map.put("data", "succeed");
			return map;
		}
	}

	@RequestMapping("testPassword")
	public @ResponseBody Map<String, Object>
	testPassword(@RequestParam String password){
        Map<String, Object> map=new HashMap<>();

		if(password.equals("")){
			map.put("data", "密码不能空");
			return map;
		}

		if(password.length()<6||password.length()>16){
			map.put("data", "'密码的长度应该在6-16个字符之间");
			return map;
		}

		map.put("data", "succeed");

		return map;

	}

	/**
     * 电话号码验证
     *
     * @param  str
     * @return 验证通过返回true
     */
	 public static boolean isPhone(String str) {
        Pattern p1 = null,p2 = null;
        Matcher m = null;
        boolean b = true;

        if(str.length()!=11){
        	return false;
        }

        return b;
     }

	@RequestMapping("/testPhone")
	public @ResponseBody Map<String, Object>
	testPhone(@RequestParam String telephone){
	    Map<String, Object> map=new HashMap<>();

		if(telephone.equals("")){
			map.put("data", "手机号码不能空");
			return map;
		}

		if(!isPhone(telephone)){
			map.put("data", "请输入正确的手机号码");
			return map;
		}

        map.put("data", "succeed");

		return map;
	}

   @RequestMapping("/testEmail")
   public @ResponseBody Map<String, Object>
   testEmail(@RequestParam String email){
	   Map<String, Object> map=new HashMap<>();

	   String regEx="[`~!#$%^&*()+=|{}':;',\\[\\]<>/?~！#￥%……&*（）——+|{}【】‘；：”“’。，、？]";
		Pattern   p   =   Pattern.compile(regEx);
	    Matcher   m   =   p.matcher(email);

	    if(m.find()){
	    	map.put("data", "Email含有非法字符");
			return map;
	    }

	    String REGEX_EMAIL = "^([a-z0-9A-Z]+[-|\\.]?)+[a-z0-9A-Z]@([a-z0-9A-Z]+(-[a-z0-9A-Z]+)?\\.)+[a-zA-Z]{2,}$";

	    if(Pattern.matches(REGEX_EMAIL, email)){
          map.put("data", "succeed");
	    }else {
	    	map.put("data", "Email地址错误");
		}
		return map;
   }

   @RequestMapping("insert")
   public @ResponseBody Integer
   insert(HttpServletRequest request,@RequestParam String name,
		   @RequestParam String headship,
		   @RequestParam String phone,@RequestParam String email,
		   @RequestParam String address,@RequestParam String regtlx){

	   HttpSession session = request.getSession();
       String openId=null;
       System.out.println("name="+name+"  headship="+headship+"   phone="
    		   +phone+"   email="+email+"    address="+address+"  regtlx="+regtlx);
       try{
         openId=session.getAttribute("openId").toString();
         }catch (Exception e) {
			// TODO: handle exception
        	 e.printStackTrace();
		  }

	   if(regtlx.equals("")){
		   return 2;
	   }

	   regtlx=regtlx.toLowerCase();

	   String verifyCode=(String) session.getAttribute("verifyCode");

	   if(!regtlx.equals(verifyCode)){
		   verifyCode=null;
		   return 2;
	   }

	   Date upTime=new Date();

	   try {
                Users users=new Users();

                users.setOpenId(openId);

				int testRepeat=userService.selectRepeatUserByOpenId(openId);

				int type;

				if(testRepeat==0){
					type=userService.insertUsersInfo(users);
				}else{
					type=userService.updateUsersInfo(users);
				}


				return type;

			}
		    catch (Exception e) {
		    	e.printStackTrace();

	            return 3;
		    }
   }

   @RequestMapping("/userinfoByopenId")
   public @ResponseBody Users
   userinfoByopenId(HttpServletRequest request,@RequestParam Integer campusId){
	   HttpSession session = request.getSession();
       String openId=null;
       try{
           openId=session.getAttribute("openId").toString();
           }catch (Exception e) {
  			// TODO: handle exception
          	 e.printStackTrace();
  		  }

       return userService.getUserInfoById(campusId, openId);
   }



	/*// 生成短信验证码
	@RequestMapping(value = "getValidate", method = RequestMethod.GET)
	public @ResponseBody Integer getValidate(@RequestParam String phone, @RequestParam String name,
											 HttpServletResponse response, HttpServletRequest request) {


		HttpSession session = request.getSession();

		String openId = session.getAttribute("openId").toString();

		HttpClient httpClient = new HttpClient();

		String requestUrl = "http://utf8.api.smschinese.cn";

		Map searchMap = new HashMap<>();

		searchMap.put("Charter like ", "%" + name.trim() + "%");

		String vcode = "";
		for (int i = 0; i < 6; i++) {
			vcode = vcode + (int) (Math.random() * 9);
		}

		String Message = "您正在进行手机验证,验证码是 : " + vcode + " , 5分钟内有效";

		System.out.println("phone=" + phone);
		System.out.println("Message=" + Message);

		WechatSendMessageController wechatSendMessageController = new WechatSendMessageController();

		int i = wechatSendMessageController.sendPhoneMessage(phone, Message, name, openId);

		System.out.println("i=" + i);

		if (i > 0) {
			LinkedHashMap<String, Map<String, Object>> linkMap = Singleton.getInstance().getRegisterMap();
			Map<String, Object> map = new HashMap<>();
			map.put("vcode", vcode);
			map.put("startTime", new Date());
			linkMap.put(phone, map);
		}

		return i;
	}*/


	@RequestMapping("test")
	public @ResponseBody Integer test(HttpServletRequest request, @RequestParam String name,
										@RequestParam String phone, @RequestParam String regtlx) {

		HttpSession session = request.getSession();
		String openId = null;

		try {
			openId = session.getAttribute("openId").toString();
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}

		if (regtlx.equals("")) {
			return 2;
		}

		try {

			regtlx = regtlx.toLowerCase();
			LinkedHashMap<String, Map<String, Object>> linkMap = Singleton.getInstance().getRegisterMap();
			Map<String, Object> map = linkMap.get(phone);

			if (map == null || map.isEmpty()) {
				return 3;
			}

			String verifyCode = (String) map.get("vcode");

			System.out.println("regtlx=" + regtlx + "      verifyCode=" + verifyCode);

			if (!regtlx.equals(verifyCode)) {
				verifyCode = null;
				return 2;
			}

			Date upTime = new Date();


			int testRepeat = userService.getCountUser_AssetByOpenId(openId);

			int type=0;

			if (testRepeat == 1) {

			} else {

			}

			return type;

		} catch (Exception e) {
			e.printStackTrace();

			return 3;
		}
	}

	/**
	 * 注册会员短信发送验证码
	 */
	@RequestMapping(value = "getValidate", method = RequestMethod.GET)
	public Integer getValidate(String phone,String name,HttpServletResponse response, HttpServletRequest request) throws UnsupportedEncodingException {

		HttpClient httpClient = new HttpClient();

		//随机验证码
		String vcode = "";
		for (int i = 0; i < 6; i++) {
			vcode = vcode + (int) (Math.random() * 9);
		}

		//发送信息的内容
		String Message = "#您正在进行手机验证,验证码是:"+vcode+",5分钟内有效";

		//组装电话号码及内容然后urlencoder
		String phoneContent=phone+Message;
		String phoneContents=java.net.URLEncoder.encode(phoneContent, "UTF-8");

		//短信发送调用URL
		String url="http://113.125.24.16:7862/sms?action=p2p&rt=json&account=800489&password=123456&mobileContentList="+phoneContents+"&extno=10690489";

		int i =Integer.parseInt(httpClient.doPost(url,null));

		if (i > 0) {
			LinkedHashMap<String, Map<String, Object>> linkMap = Singleton.getInstance().getRegisterMap();
			Map<String, Object> map = new HashMap<>();
			map.put("vcode", vcode);
			map.put("startTime", new Date());
			linkMap.put(phone, map);
		}

		return i;
	}


}
